let tom = {
  name: "tom",
  age: 10,
  eat: function () {
    console.log("eat");
  },
  father: {
    name: "tomFather",
    age: 10,
    work: function () {
      console.log("work");
    },
  },
};

// Object.assign()
console.log(tom);
let newTom = {};
Object.assign(newTom, tom);
console.log(newTom);

newTom.father.name = "newTom";
console.log(tom);
console.log(newTom);

//
function deepClone(oldObj) {
  if (typeof oldObj !== "object") return oldObj;
  let newObj = Array.isArray(oldObj) ? [] : {};
  for (let key in oldObj) {
    if (oldObj.hasOwnProperty(key)) {
      newObj[key] = typeof newObj[key] === "object" ? deepClone(oldObj[key]) : oldObj[key];
    }
  }
  return newObj;
}

function deepClone(obj, hash = new WeakMap()) {
  if (obj === null) return obj; // 如果是null或者undefined，直接返回
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof RegExp) return new RegExp(obj);
  // 如果不是普通对象，直接返回
  if (typeof obj !== "object") return obj;
  // 检查是否已经是循环引用过的对象
  if (hash.get(obj)) return hash.get(obj);
  let cloneObj = new obj.constructor();
  // 记录当前对象
  hash.set(obj, cloneObj);
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      // 递归克隆子属性
      cloneObj[key] = deepClone(obj[key], hash);
    }
  }
  return cloneObj;
}

function deepCopy(obj, hash = new WeakMap()) {
  // 如果不是对象类型，直接返回
  if (typeof obj !== "object" || obj === null) {
    return obj;
  }

  // 检查是否已经是循环引用过的对象
  if (hash.has(obj)) {
    return hash.get(obj);
  }

  // 根据对象类型创建新对象
  let newObj;
  if (Array.isArray(obj)) {
    newObj = [];
  } else if (obj instanceof Date) {
    return new Date(obj.getTime());
  } else if (obj instanceof RegExp) {
    return new RegExp(obj);
  } else if (obj instanceof Function) {
    return obj;
  } else {
    newObj = {};
  }

  // 记录当前对象
  hash.set(obj, newObj);

  // 遍历对象属性
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = deepCopy(obj[key], hash);
    }
  }

  return newObj;
}

const newObj = JSON.parse(JSON.stringify(obj));
